package com.ash.b.structural.proxy.dynamics;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 代理处理器，对接口的所有方法进行增强
 *
 * @author Ash
 */
public class DynamicSubjectProxy implements InvocationHandler {

    private Object sub;

    private DynamicSubjectProxy(Object obj) {
        sub = obj;
    }

    @SuppressWarnings("unchecked")
    public static <T> T newProxy(T target) {
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new DynamicSubjectProxy(target));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before calling  " + method);

        Object result = method.invoke(sub, args);

        System.out.println("after calling  " + method);

        return result;
    }

}
